package db_main

import (
	"errors"
	"fmt"
	"gorm.io/gorm"
	"longmen/server/config/global"
	"longmen/server/pkg/common/helper/util"
	"longmen/server/pkg/db/mysql"
	"longmen/server/pkg/db/mysql/models/models_main"
)

func GetStatisticsParam(param map[string]interface{}) (*models_main.Statistics, error) {
	fName := "GetStatisticsParam"
	o := &models_main.Statistics{}
	table := mysql.GetRTable(&models_main.Statistics{})
	mysql.Condition(table, param, "", "", 0, 0)
	err := table.Find(o).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		err = nil
	}
	if err != nil {
		err = fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	return o, err
}

func UpdateStatistics(id, column string, statistics *models_main.Statistics) error {
	fName := "UpdateStatistics"
	if len(column) <= 0 {
		return nil
	}

	result := global.GetX().Exec(fmt.Sprintf("UPDATE %s SET %s = %s + 1 WHERE id = ?", (&models_main.Statistics{}).TableName(), column, column), id)
	if result.Error != nil {
		return fmt.Errorf("%s%s", util.Convert(fName), result.Error.Error())
	}

	if result.RowsAffected <= 0 {
		err := global.GetX().Create(statistics).Error
		if err != nil {
			return fmt.Errorf("%s%s", util.Convert(fName), err.Error())
		}
		return nil
	}
	return nil
}

func UpdateStatisticsByTransactions(session *gorm.DB, id, column string, statistics *models_main.Statistics) error {
	fName := "UpdateStatisticsByTransactions"
	result := session.Exec(fmt.Sprintf("UPDATE %s SET %s = %s + 1 WHERE id = ?", (&models_main.Statistics{}).TableName(), column, column), id)
	if result.Error != nil {
		session.Rollback()
		return fmt.Errorf("%s%s", util.Convert(fName), result.Error.Error())
	}

	if result.RowsAffected <= 0 {
		err := session.Create(statistics).Error
		if err != nil {
			session.Rollback()
			return fmt.Errorf("%s%s", util.Convert(fName), err.Error())
		}
		return nil
	}
	return nil
}
